package com.hxci.zhongjiahao.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.time.LocalDate;

@RestController("zhongjiahaoOpenAIController")
public class OpenAIController {

	private final ChatClient chatClient;

	public OpenAIController(ChatClient.Builder builder, VectorStore vectorStore, ChatMemory chatMemory) {
		this.chatClient = builder
				.defaultSystem("""
                    您是"哈尔滨信息工程学院课程管理系统"的智能助手。
                    今天的日期是 {current_date}。
                    您可以回答课程相关问题，也可以调用函数添加、删除、查询课程。
                    """)
				.defaultAdvisors(
						new PromptChatMemoryAdvisor(chatMemory),
						new QuestionAnswerAdvisor(vectorStore)
				)
				.defaultFunctions("addCourse", "deleteCourse", "getCourseDetails")
				.build();
	}

	@GetMapping(value = "/ai/generateStreamAsString", produces = "text/event-stream")
	public Flux<String> generateStreamAsString(@RequestParam("message") String message) {
		return chatClient.prompt()
				.system(s -> s.param("current_date", LocalDate.now().toString()))
				.user(message)
				.stream()
				.content()
				.concatWith(Flux.just("[complete]"));
	}
}